package com.hy.myapp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.hy.myapp.Entity.User;

@Component
public class Interceptor implements HandlerInterceptor{
	private final static Logger logger = LoggerFactory.getLogger(Interceptor.class);
	
    /**
     * 在请求处理之前进行调用（Controller/RestController方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    	// System.out.println("有请求来到，其路径="+request.getServletPath());
    	String path = request.getServletPath();
    	if(path.startsWith("/lib/") || path.startsWith("/stylesheets/")|| path.startsWith("/assets/") || path.startsWith("/images/")) {
    		return true;
    	}
    	logger.info("Request coming,whose path={}",path);
    	
    	// 执行权限检查、登录验证、缓存处理等
    	HttpSession session=request.getSession();
    	User user = (User)session.getAttribute("user");
        if(user==null)
        {
            System.out.println("User dosen't login in.");
            try {
				response.sendRedirect(request.getContextPath()+"/");
			} catch (Exception e) {
				e.printStackTrace();
			}
            return false;
        }else {
        	System.out.println("User loginned in.");
        }
    	
        return true;
    }
}
